import storage from "@/utils/storage";
import baseApi from "@/config/baseApi.js";

const optionsDef = {
	count: 1,
	sizeType: ['original', 'compressed'],
	sourceType: ['album', 'camera']
}

// 选择上传图片
const chooseUploadImg = (data, options = optionsDef) => {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: options.count,
			sizeType: options.sizeType,
			sourceType: options.sourceType,
			success: (res) => {
				uni.uploadFile({
					url: baseApi.uploadFileApi,
					header: {
						'token': storage.getToken()
					},
					file: res.tempFilePaths[0],
					name: 'file',
					success: (fileRes) => {
						let data = JSON.parse(res.data)
						resolve(data)
					}
				})
			},
			fail: err => {
				console.log(err.errMsg)
			}
		})
	})
}

// 解密电话号码，需要获取电话号码授权的加密信息和解密所需的sessionKey
const phoneDecrypt = (e, sessionKey) => {
	return new Promise((resolve, reject) => {
		if (e.detail.errMsg == "getPhoneNumber:ok") {
			const appid = uni.getAppBaseInfo().host.appId;
			const phoneDec = require('./phoneDec.js')
			let pc = new WXJM(appid, sessionKey)
			let data = pc.decryptData(e.detail.encryptedData, e.detail.iv)
			resolve(data.phoneNumber)
		} else {
			reject()
		}
	})
}


export const randomLenNum = (len, date) => {
	let random = ''
	random = Math.ceil(Math.random() * 100000000000000)
		.toString()
		.substr(0, len || 4)
	if (date) random = random + Date.now()
	return random
}

export const is2DArray = (arr) => {
	if (!Array.isArray(arr)) {
		return false; // 不是数组
	}

	return arr.some(element => Array.isArray(element));
}

//tree转list
export const treeToList = (tree) => {
	return tree.reduce((arr, node) => {
		const { children, ...other } = node
		arr.push(other);
		if (children) {
			const childArr = treeToList(children);
			arr.push(...childArr);
		}
		return arr;
	}, []);
}

export function buildFileUrl(bucket, objectName) {
	return `${baseApi.baseFileApi}/${bucket}/${objectName}`
}

// 实现Base64加密
export function base64Encode(str) {
	let base64 = new Base64();
	return base64.encode(str);
}

// 实现Base64解密
export function base64Decode(str) {
	let base64 = new Base64();
	return base64.decode(str);
}

// 定义Base64对象
function Base64() {

	// Base64字符集
	const base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

	// 编码函数
	this.encode = function (str) {
		let result = '';
		for (let i = 0; i < str.length; i += 3) {
			let a = str.charCodeAt(i);
			let b = i + 1 < str.length ? str.charCodeAt(i + 1) : 0;
			let c = i + 2 < str.length ? str.charCodeAt(i + 2) : 0;

			let a1 = a >> 2, a2 = ((a & 3) << 4) | (b >> 4), a3 = ((b & 15) << 2) | (c >> 6), a4 = c & 63;

			result += base64Chars[a1] + base64Chars[a2] + (i + 1 < str.length ? base64Chars[a3] : '=') + (i + 2 < str.length ? base64Chars[a4] : '=');
		}
		return result;
	}

	// 解码函数
	this.decode = function (str) {
		let result = '';
		let i = 0;
		while (i < str.length) {
			let a = base64Chars.indexOf(str.charAt(i++));
			let b = base64Chars.indexOf(str.charAt(i++));
			let c = base64Chars.indexOf(str.charAt(i++));
			let d = base64Chars.indexOf(str.charAt(i++));

			let a1 = (a << 2) | (b >> 4);
			let a2 = ((b & 15) << 4) | (c >> 2);
			let a3 = ((c & 3) << 6) | d;

			result += String.fromCharCode(a1);
			if (c != 64) {
				result += String.fromCharCode(a2);
			}
			if (d != 64) {
				result += String.fromCharCode(a3);
			}
		}
		return result;
	}
}



export default {
	chooseUploadImg,
	phoneDecrypt,
}
